<template>
  <el-upload
    class="file-uploader"
    drag
    :action="action"
    :auto-upload="autoUpload"
    :multiple="multiple"
    :limit="limit"
    :on-exceed="handleExceed"
    :before-upload="beforeUpload"
    :on-change="handleChange"
    :show-file-list="showFileList"
    :accept="accept"
  >
    <i class="el-icon-upload"></i>
    <div class="el-upload__text">
      将文件拖到此处，或<em>点击上传</em>
    </div>
    <div class="el-upload__tip" slot="tip" v-if="tip">
      {{ tip }}
    </div>
  </el-upload>
</template>

<script>
export default {
  props: {
    action: {
      type: String,
      default: ''
    },
    autoUpload: {
      type: Boolean,
      default: false
    },
    multiple: {
      type: Boolean,
      default: false
    },
    limit: {
      type: Number,
      default: 1
    },
    showFileList: {
      type: Boolean,
      default: true
    },
    accept: {
      type: String,
      default: '.doc,.docx,.pdf'
    },
    tip: {
      type: String,
      default: '只能上传doc/docx/pdf文件，且不超过20MB'
    },
    maxSize: {
      type: Number,
      default: 20 // MB
    }
  },

  methods: {
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 ${this.limit} 个文件`)
    },

    beforeUpload(file) {
      const isLtMaxSize = file.size / 1024 / 1024 < this.maxSize
      if (!isLtMaxSize) {
        this.$message.error(`文件大小不能超过 ${this.maxSize}MB!`)
      }
      return isLtMaxSize
    },

    handleChange(file, fileList) {
      this.$emit('change', file, fileList)
    }
  }
}
</script>

<style scoped>
.file-uploader {
  margin-bottom: 20px;
}
</style>
